package com.googlecode.entity_dao.core.dao.hibernate;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import com.googlecode.entity_dao.core.dao.PersistentEnumerationDao;
import com.googlecode.entity_dao.core.entity.PersistentEnumeration;

/**
 * Generic persistent enumeration DAO implementation using JPA / Hibernate persistence APIs.
 * 
 * @param <T> Type of the persistent enumeration the DAO works with.
 * @param <ID> Java type of persistent entity's primary key column.
 * 
 * @see PersistentEnumerationDao
 * @see AbstractHibernateEntityDao
 * 
 * @author mauro.franceschini
 */
public abstract class AbstractHibernateEnumerationDao<T extends PersistentEnumeration<ID>, ID extends Serializable>
        extends AbstractHibernateEntityDao<T, ID> {

    public <S extends T> S getByName(String name, Class<S> targetEntityClass) {
        Criteria criteria = getHibernateCriteria(targetEntityClass);
        criteria.add(Restrictions.eq(PersistentEnumeration._NAME, name));

        return targetEntityClass.cast(criteria.uniqueResult());
    }

    public T getByName(String name) {
        return getByName(name, getEntityClass());
    }

    @SuppressWarnings("unchecked")
    public <S extends T> List<S> getByNames(Class<S> targetEntityClass, String... names) {
        Criteria criteria = getHibernateCriteria(targetEntityClass);
        criteria.add(Restrictions.in(PersistentEnumeration._NAME, Arrays.asList(names)));

        return criteria.list();
    }

    public List<T> getByNames(String... names) {
        return getByNames(getEntityClass(), names);
    }
}
